import 'package:tobias/tobias.dart';
import 'dart:developer' as developer;
import 'payment_service_interface.dart';

/// 真实设备的支付宝支付服务实现
class AlipayServiceReal implements PaymentServiceInterface {
  
  @override
  Future<void> init() async {
    try {
      // tobias库不需要显式初始化
      final isInstalled = await isAliPayInstalled();
      developer.log('✅ 支付宝SDK初始化成功, 支付宝已安装: $isInstalled');
    } catch (e) {
      developer.log('💥 支付宝SDK初始化失败: $e');
    }
  }

  @override
  Future<bool> isInstalled() async {
    try {
      return await isAliPayInstalled();
    } catch (e) {
      developer.log('检查支付宝安装状态失败: $e');
      return false;
    }
  }

  @override
  Future<Map<String, dynamic>?> pay(String orderString) async {
    try {
      developer.log('🔄 开始支付宝支付');
      
      // 调起支付宝支付
      final result = await aliPay(orderString);
      
      developer.log('支付结果: ${result.toString()}');
      
      // 转换为Map<String, dynamic>
      final resultMap = Map<String, dynamic>.from(result);
      
      // 解析支付结果
      final resultStatus = resultMap['resultStatus'];
      switch (resultStatus) {
        case '9000':
          developer.log('✅ 支付成功');
          return resultMap;
        case '8000':
          developer.log('⚠️ 支付正在处理中');
          return resultMap;
        case '4000':
          developer.log('❌ 订单支付失败');
          return resultMap;
        case '5000':
          developer.log('❌ 重复请求');
          return resultMap;
        case '6001':
          developer.log('🚫 用户中途取消');
          return resultMap;
        case '6002':
          developer.log('⚠️ 网络连接出错');
          return resultMap;
        default:
          developer.log('❓ 未知的支付状态: $resultStatus');
          return resultMap;
      }
    } catch (e) {
      developer.log('💥 支付宝支付异常: $e');
      return null;
    }
  }
}
